package com.acg.util;


import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @Description TODO
 * @Author 没有脑袋
 * @Date 2025/7/31 14:11
 */
public class JwtHelper {

    // 设置token过期时间
    private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;

    // 设置token签名 (key)   自定义的
    private static String tokenSignKey = "123456";

    public static String createToken(Long userId, String username) {
        String token = Jwts.builder()
                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)                // 放置的载荷
                .claim("username", username)            // 放置的载荷
                .signWith(SignatureAlgorithm.HS256, tokenSignKey)   // token 签名  key
                .compressWith(CompressionCodecs.GZIP)               // 进行压缩  压缩算法
                .compact();
        return token;
    }


    /**
     * 根据token获取userId
     * @param token token获取userId
     * @return
     */
    public static Long getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) return null;

            // 解析token 获取载荷中的userId
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            // 获取载荷
            Claims claims = claimsJws.getBody();

            // 获取数据
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从token 获取用户名
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)) return "";

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken(1L, "admin");
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getUsername(token));
    }

}
